import {
  api,
  util,
  dialog,
} from '../../../../js/util';
import {
  share
} from "../../../../js/modules/gloab";
import {
  pagesInfo,
  router
} from '../../../../js/router';
import {
  $ecCountDown
} from '../../../../components/index.js'
import {
  profile
} from "../../../../js/modules/store.js";
import {
  detail,
  mall,
  list,
  comments
} from '../../../../js/modules/mall';
import {
  activities,
  group,
  coupon
} from '../../../../js/modules/market';
import {
  order,
  cart,
  grouporder
} from '../../../../js/modules/order';
import authorize from '../../../../js/modules/authorize';
import BasePage from '../../../../js/common/base-page'
import { theme } from '../../../../js/modules/theme';
var app = getApp();
BasePage({
  pageKey: "",
  /**
   * 页面的初始数据
   */
  data: {
    isselect: 'img',
    imgDomain: api.imgDomain,
    enableOss: api.enableOss,
    pagetype: 0, //0:通用 1:拼团  2:预售 3:特价
    gsmbg: "", //group:拼团头部   presale:预售头部   sale:特价
    id: 0,
    productId: 0,
    discountId: 0,
    discountType: 0,
    productData: [],
    editionInfo:null,
    annexs:[],
    groupType: 2,
    goodSpecific: [],
    productUnitText: "",
    pricerules: [],
    groupruleList: [],
    swiperImg: [],
    productVideo: {},
    IsStart: 1,
    tablist: ['图文详情', '商品参数', '售后保障'],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 10,
    slidewidth: 0,
    showStyle: 'view',
    guessList: [], //猜你喜欢商品列表
    hasCang: '', //是否收藏
    FavouriteId: 0, //收藏Id
    isCanBuy: false, //是否可以购买  用于拼团预售
    IsLimit: false, //是否限购一单  用于拼团预售
    Attributes: [], //扩展属性
    current_sku_item: {},
    quantityDigits: 0,
    priceDigits: 2,//价格显示小数位数
    goodsIndex:0,
    proprietorWaterMark: "",//图片水印
    showPosterShadow: false, //海报弹层
    windowWidth: 0, //屏幕宽度
    windowHeight: 0,//屏幕高度
    contentHeight: 0,//内容高度
    thinkList: [], //文字超出换行处理
    lineHeight: 30, //固定值
    contentTitle: "", //商品标题
    subTitle:'',  //副标题
    price: "",//商品价格
    delPrice: "",//划线价
    canvasUrl: "",
    qrCode: "", //小程序码https图片路径
    goodsInfoImg: "",  //商品图片
    logo: "",
    downlogo: "",
    saveBtn: false,//保存图片按钮
    enableSKUTranslated: true,  //不同规格单位换算关系不相同
    mainColor:'',//主题色
    isIphoneX:app.globalData.isIphoneX,//适配手机
    Currency:'',//货币符号
    isLogin: true,
    NoLoginShowPrice:false,//
    openComment: false, //是否开启评价
    productCommentInfo: {}, //商品评论信息
    barStyle: '2', // 顶部导航样式，2文字居中，3透明顶部
    navigationTitle: '商品详情'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log('拼团预售onload', options)
    if (!authorize.isLogin("store")) {
      authorize.redirect("store");
      return;
    }
    if (options.id <= 0 && !options.scene) {
      //数据加载错误
      return;
    }
    //解析扫描拼团和预售详情小程序码中的scene
    if (options.scene && options.scene.indexOf("_")>-1) {
      let scene = decodeURIComponent(options.scene);
      if(scene.split("_").length==5){
        //_是我们定义的参数链接方式
        options.id = scene.split("_")[0];
        options.ptype = scene.split('_')[1];
        options.productId = scene.split('_')[2];
        options.discountid = scene.split('_')[3];
        options.discounttype = scene.split('_')[4];
      }
    }
    var pagetype = options.ptype || 0;
    var gsmbg = ""; ///group:拼团头部   presale:预售头部   sale:特价
    //拼团预售
    gsmbg = pagetype == 1 ? "group" : "presale";

    this.setData({
      pagetype: pagetype,
      id: options.id || 0,
      productId: options.productId || 0,
      discountId: options.discountid || 0,
      discountType: options.discounttype || 0,
      itemId: options.itemId || 0,
      gsmbg: gsmbg
    });
    this.pageKey = pagetype == 1 ? 'groupDetail' : 'presellDeail';
    //加载促销详情
    this.loadGroupDetail(pagetype);
    //商品扩展属性
    this.loadProductRelate();
    this.getWholesaleConfig();
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          slidewidth: (res.windowWidth / that.data.tablist.length) - 20,
        });
      }
    });
    this.getShareInfo();
  },

  /**倒计时 */
  setCountdown(time) {
    this.c1 = new $ecCountDown({
      date: time,
      render(date) {
        const days = this.leadingZeros(date.days, 2)
        const hours = this.leadingZeros(date.hours, 2)
        const min = this.leadingZeros(date.min, 2)
        const sec = this.leadingZeros(date.sec, 2)
        this.setData({
          c1: days,
          c2: hours,
          c3: min,
          c4: sec
        })
      },
    });
  },
  /**加载商品类的配置项参数 */
  getWholesaleConfig() {
    var that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    list.getWholesaleConfigs(
      fkid,
      fkflag,
      function (content) {
        that.setData({
          quantityDigits: content.QuantityDigits,
          priceDigits: content.PriceDigits,
          isScanty: content.IsScanty, //是否允许缺货登记
          proprietorWaterMark: content.ProprietorWaterMark,
          logo: content.LogoForMobile,
          NoLoginShowPrice:content.NoLoginShowPrice,//0：建议零售价 1：不显示价格
          activeIndex:Number(content.MIntroDefaultTab),
          openComment: content.OpenComment,
        });
      });
  },
  /**检验拼团预售商品是否可以购买 */
  isGroupCanBuy(levelIds, limitOrders) {
    var that = this;
    var entity = authorize.getEntity();
    if (levelIds != null && levelIds != undefined && levelIds != "" && ("," + levelIds + ",").indexOf("," + entity.role.LevelId + ",") < 0) {
      that.setData({
        isCanBuy: false
      });
      return false;
    }
    if (limitOrders == null || limitOrders == undefined || limitOrders == "") {
      that.setData({
        isCanBuy: true,
        IsLimit: false
      });
      return true;
    }
    var param = {
      GroupId: this.data.id,
      Flag: this.data.pagetype,
      entity: entity
    }
    var that = this;
    activities.getGroupOrderCount(param, function(res) {
      var isCanBuy = parseInt(res) >= parseInt(limitOrders) ? false : true;
      that.setData({
        isCanBuy: isCanBuy,
        IsLimit: !isCanBuy
      });
    });
  },
  /**加载拼团预售商品详情 */
  loadGroupDetail(pagetype) {
    var param = {
      Id: this.data.id,
      flag: pagetype,
      ItemId: this.data.itemId,
      pid: this.data.productId
    }
    var that = this;
    detail.loadProductDetail(pagetype, param, function(res) {
      // if(!res.Success){
      //   util.alert("对不起，该商品不能访问了");
      //   router.navigateBack({});
      //   return;
      // }
      res=res.Content;
      //组装图片为组件可用的对象
      var pics = [];
      for (var i = 0; i < res.Pics.length; i++) {
        var p = res.Pics[i];
        if (p.VirtualPath != "" && p.VirtualPath != undefined) {
          pics.push({
            Src: p.VirtualPath
          });
        }
      }
      var productData = res.GroupProduct[0],
          editionInfo = (res.EditionInfo && Object.keys(res.EditionInfo).length > 0) ? res.EditionInfo : null,
          annexs = res.Annexs || [];
      //适用于通用变量
      productData.fkid = productData.FKId;
      productData.FavouriteId = productData.FavoriteId;
      productData.fkname = res.ShopName;
      if(res.SupplierProduct && res.SupplierProduct[0]!=undefined){
        var sp = res.SupplierProduct[0]; //供应商品特有的一些字段
        productData.ShowStandIntro = sp.ShowStandIntro;
      }
      var actualQuantity = productData.ActualQuantity;
      var prices = res.Pricerules; //阶梯价
      if (prices && prices.length > 0) {
        var nowPrice = prices[0].Price; //当前价格
        var nextPrice = nowPrice; //下一级价格
        var nextQuantity = prices[0].MinQuantity; //下一级数量
        for (var i = 0; i < prices.length; i++) {
          var p = prices[i];
          var minQuantity = p.MinQuantity;
          var maxQuantity = p.MaxQuantity;
          if (i < prices.length - 1){
            if ((minQuantity < actualQuantity && actualQuantity < prices[i + 1].MinQuantity) || (minQuantity == actualQuantity) || (actualQuantity == maxQuantity && maxQuantity != 0) || (minQuantity < actualQuantity && maxQuantity == 0)){
              nowPrice = p.Price;
              nextQuantity = prices[i + 1].MinQuantity;
              nextPrice = prices[i + 1].Price;
              break;
            }   
          }else{
            if ( (minQuantity == actualQuantity) || (actualQuantity == maxQuantity && maxQuantity != 0) || (minQuantity < actualQuantity)) {
              nowPrice = p.Price;
              nextQuantity = 0;
              break;
            }  
          }
        }
        productData.NowPrice = nowPrice;
        productData.NextPrice = nextQuantity == 0 ? 0 : nextPrice;
        productData.ToNextQuantity = nextQuantity == 0 ? 0 : nextQuantity - actualQuantity;
        productData.DefaultUnit = productData.Unit;
      }
      try {
        //解析京东外部链接style里面的背景图 
        util.linkParseImg(productData.Intro,(intro)=>{
          let content = util.decoratePicSrc(intro, that.data.imgDomain);
          content = content.replace(/()+/ig, "\n");
          that.setData({
            richtext_content: content
          })
        });
        var guarantee = util.decoratePicSrc(productData.Guarantee || "", that.data.imgDomain);
        that.setData({
          richtext_guarantee: guarantee
        })
      } catch (e) {

      }
      //当前时间
      var isStart = 1;
      var nowDate = new Date();
      var starttime = new Date(Date.parse(productData.BeginTime));
      if (starttime > nowDate) {
        isStart = 0;
        that.setCountdown(productData.BeginTime);
      } else {
        that.setCountdown(productData.EndTime);
      }
      //是否限购
      that.isGroupCanBuy(productData.LevelIds, productData.LimitOrders);
      for (var i in res.AuxiliaryUnit) {
        if (res.AuxiliaryUnit[i].IsDefaultUnit == 1) {
          productData.DefaultUnit = res.AuxiliaryUnit[i].Name;
          productData.Translated = res.AuxiliaryUnit[i].Translated;
        }
      }
      that.setData({
        productId: productData.ProductId,
        productData: productData,
        editionInfo:editionInfo,
        annexs:annexs,
        swiperImg: pics,
        pics: pics,
        groupruleList: res.Pricerules,
        groupType: res.GroupType,
        IsStart: isStart,
        FavouriteId: productData.FavoriteId,
        productVideo:res.ProductVideo[0]
      });

      that.loadGroupSpecifics(pagetype, productData);
      //抓取数据
      let pageTitle = pagetype == 1 ? '拼团商品详情' : '预售商品详情';
      that.pageInfo={
        pageTitle: pageTitle,
        detailText: productData.ProductName,
        parameter: `ProductId=${productData.ProductId}&Id=${that.data.id}`
      };

    });
    setTimeout(() => {
      // console.log(that.data.isCanBuy ,'=========',that.data.IsLimit)
      if(!that.data.isCanBuy && !that.data.IsLimit){
        router.reLaunch({
          path: "productDetail",
          params:{
            id: that.data.productData.ProductId
          }
        });
      }
    }, 800);
  },
  /**加载拼团预售规格列表 */
  loadGroupSpecifics(pagetype, productData) {
    var that = this;
    let { goodsIndex}=this.data;
    detail.loadGroupGoods(this.data.id, pagetype, function(content) {
      productData.MaxPrice = productData.MaxPrice || 0;
      for (var i = 0; i < content.length; i++) {
        var g = content[i];
        // if (productData.MaxPrice < g.MaxPrice) {
        //   // productData.MaxPrice = pagetype == 2?productData.MaxPrice:g.MaxPrice
        //   productData.MaxPrice = productData.MaxPrice
        // }        
        g.Translated = productData.Translated;
        g.CartCount = 0;
        g.Unit = productData.Unit;
        g.DefaultUnit = g.AuxUnit;
        //数量为0时，默认显示最小价格
        let minPrice = g.MaxPrice;
        if(g.CartCount == 0){
          g.PriceRules.map((item)=>{
            if(item.Price < minPrice){
              minPrice = item.Price;
            }
          })
        }
        // g.SalesPrice = minPrice; //g.MaxPrice;
        
        g.Stock = util.calulateReduce(g.Quantity,g.ActualQuantity);
        var upperlimit = (productData.BuyMaxQuantity != 0 && productData.BuyMaxQuantity < g.Stock) ? productData.BuyMaxQuantity : g.Stock; 
        g.BuyUpperLimit = upperlimit;
        g.BuyLowerLimit = productData.BuyMinQuantity;
        let units = g.AuxiliaryUnits;
        g.ZIndex = 1;
        
        if (units && units.length > 0) {
          for (let j = 0; j < units.length; j++) {
            // if (g.DefaultUnit == units[j].Name) {
              if (units[j].IsDefaultUnit == 1) {
              g.ZIndex = j;
              g.Translated = units[j].Translated;
              productData.Translated = units[j].Translated;
              productData.DefaultUnit = units[j].Name;
              break;
            }
          }
        }
        if (productData.GroupItemId == g.GroupItemId) {
          goodsIndex=i;
          that.data.current_sku_item = g;
          productData.SalesPrice = g.SalesPrice;
        }
        var data = {
          translated: productData.Translated,
          rule: g.PriceRule || g.PriceRules,
          priceType: 0
        };
        var price_obj = group.parseRule(data, 0);
        // console.log(price_obj,'-----==price_obj');
        if (price_obj.has) {
          //如果价格没有变化时，则不给数据源重新绑定值
          if (g.SalesPrice != price_obj.price || (g.SalesIntegral || 0) != (price_obj.integral || 0)) {
            g.SalesIntegral = price_obj.integral;
            g.SalesPrice = price_obj.price;      
          }
        }
      }
      //如果不同规格单位换算关系相同，则构建转换关系文本
      let productUnitText = '';
      if(productData.EnableSKUTranslated!=1){
        let units = content[0].AuxiliaryUnits||[];
        productUnitText = detail.loadUnitContext(units, productData.Unit); //批发规则
      }
      // console.log(productUnitText,'=====productUnitText',content);
      that.setData({
        productData: productData,
        goodsIndex: goodsIndex,
        goodSpecific: content,
        productUnitText:productUnitText,
        current_sku_item: that.data.current_sku_item,
        enableSKUTranslated: productData.EnableSKUTranslated==1?true:false
      });
      that.getCommentsInfo();
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function(options) {
    console.log('拼团预售onshow', options)
    this.setData({
      mainColor:api.titleColor||"#e56b14", 
      Currency:api.Currency || '￥',
      isLogin:authorize.isLogin('store')
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    // wx.navigateBack({
    //   delta: 0
    // })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  /**
   * 获得评论信息
   */
  getCommentsInfo() {
    let that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    comments.getCommentsInfo({
      pid: that.data.productId,
      gid: 0,
      fkFlag: fkflag,
      fkId: fkid
    }, function(res) {
      if (res.Success) {
        that.setData({
          productCommentInfo: res.Content
        });
      }
    });
  },
  /**
   * 下载附件
   */
  loadFile:function(e){
    let url = this.data.imgDomain + e.currentTarget.dataset.url;
    let type = e.currentTarget.dataset.type;
    wx.downloadFile({
      url: url,
      success: function (res) {
        if(type=='png'||type=='jpeg'||type=='gif'||type=='jpg'){
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success(res) {
              wx.showModal({
                content: '图片已下载到相册',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  if (res.confirm) { }
                },
                fail: function (res) { }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: "下载失败",
                icon: 'none',
                duration: 2000
              })
            }
          })
        }else{
          wx.saveFile({
            tempFilePath:res.tempFilePath,
            success(res){
              wx.showModal({
                content: '文件已下载成功',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  if (res.confirm) { }
                },
                fail: function (res) { }
              })
            }
          })
        }
      },
      fail: function (err) {
        util.tips(err.errMsg);
      }
    })
  },
  /**
   * 获取分享信息
   */
  getShareInfo:function(){
    let that = this;
    let {productId,productData,discountType,discountId} = that.data;
    let param = {
        Proprietor:app.dns.proprietor,
        ProprietorId:app.dns.proprietorId,
        ProductId:productId,
        DiscountType:discountType,
        DiscountId:discountId,
        Type:'product'
    }
    share.getinfo(param,false,function(res){
        let shareObj = {};
        shareObj.title = res.Title || productData.ProductName;
        shareObj.img = res.ImgSrc!=''?api.imgDomain+res.ImgSrc:'';
        that.setData({
            shareObj:shareObj
        })
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    let { id, pagetype, shareObj, productId } = this.data;
    var storeInfo = authorize.getEntity();
    let scene="";
    if(storeInfo){
      scene=storeInfo.fkFlag+"_"+storeInfo.fkId+"_"+storeInfo.manager.ManagerId;
    } 
    let path = pagesInfo.groupDetail.url+ `?id=${id}&productId=${productId}&ptype=${pagetype}&scene=${scene}`;
    return {
      title: shareObj.title,
      path: path,
      imageUrl: shareObj.img
    }
  },
  changeCurrent: function(res) {
    this.setData({
      sliderOffset: res.detail.currentNum.offsetLeft,
      activeIndex: res.detail.currentNum.id
    });
  },
  //底部收藏
  onFavourite: function() {
    var favouriteId = this.data.FavouriteId;
    if (favouriteId > 0) {
      this.delFavorite(favouriteId);
    } else {
      this.addFavorite();
    }
  },
  /**添加收藏 */
  addFavorite() {
    var param = {
      ProductFKId: this.data.productData.fkid,
      ProductId: this.data.productId
    };
    var that = this;
    mall.addFavorite(param, function(res) {
      if (res.Content > 0) {
        that.setData({
          FavouriteId: res.Content
        });
        util.success("商品收藏成功！");
      } else {
        util.tips(res.Message);
      }
    });
  },
  /**取消收藏 */
  delFavorite(favouriteId) {
    var that = this;
    mall.delFavorite(favouriteId, function(res) {
      if (res.Content == 1) {
        that.setData({
          FavouriteId: 0
        });
        util.success("取消收藏成功！");
      } else if (res.Content == -11) {
        util.tips("请先登录，再进行此操作！");
      } else {
        util.tips(res.Message);
      }
    });
  },

  /**判断是否登录 */
  isLogin() {
    if (!authorize.isLogin('store')) {
      authorize.redirect('store');
      return;
    }
  },
  /**即将开始提示 */
  showTip() {
    util.tips(this.data.productData.BeginTime +"开始，敬请关注！");
  },
  /**
   * 数量改变
   */
  onNumChage: function(e) {
    var that = this;
    var num = e.detail.value;

    var goodSpecific = this.data.goodSpecific;
    var g = null,
      idx = 0;
    if (this.data.pagetype == 1 && this.data.groupType == 2) {
      for (var i in goodSpecific) {
        if (goodSpecific[i].GroupItemId == this.data.productData.GroupItemId) {
          idx = i;
          g = goodSpecific[idx];
          break;
        }
      }
    } else {
      idx = e.detail.idx;
      g = goodSpecific[idx];
    }
    if (g == null) return;

    g.Translated = g.Translated || 1;
    g.PriceType = 0;
    var data = {
      translated: g.Translated,
      rule: g.PriceRule || g.PriceRules,
      priceType: g.PriceType
    };
    g.CartCount = num;
    //获得阶梯价格
    var price_obj = group.parseRule(data, num);
    if (price_obj.has) {
      //如果价格没有变化时，则不给数据源重新绑定值
      if (g.SalesPrice != price_obj.price || (g.SalesIntegral||0) != (price_obj.integral||0)) {
        g.SalesIntegral = price_obj.integral;
        g.SalesPrice = price_obj.price;
        that.data.goodSpecific[idx] = g;
        that.setData({
          goodSpecific: that.data.goodSpecific,
          current_sku_item:g
        });
      }
    }
  },
  /**
   * 切换sku
   */
  onSwitchSkuSpecEvent: function(e) {
    var index = e.currentTarget.dataset.index;
    var item = this.data.goodSpecific[index];
    var itemId = 0;
    let {pagetype}=this.data;
    this.setData({
      itemId: item.GroupItemId
    },()=>{
      this.loadGroupDetail(pagetype);
    })
   
    
  },
  /**拼团预售下单 */
  buyNowToGroup() {
    //判断是否登录
    this.isLogin();
    var flag = this.data.pagetype;
    var goodslist = this.data.goodSpecific;
    var goodsMode = this.data.productData;
    var productinfo = grouporder.buyNowToGroup(flag, this.data.groupType, goodslist, goodsMode,this.data.quantityDigits);
    if (productinfo == '') {
      util.tips("请确定货品购买数量");
      return;
    }
    var param = {
      SellerFKId: goodsMode.FKId,
      GroupId: goodsMode.Id,
      GoodsInfo: productinfo
    }
    grouporder.groupCanbuy(param, function() {
      var p = {
        path: "groupConfirm",
        params: {
          productinfo: productinfo,
          flag: flag
        }
      }
      router.navigate(p);
    });

  },
  /**单独购买 */
  buytoCommomProduct() {
    router.navigate({
      path: "productDetail",
      params:{
        id: this.data.productData.ProductId
      }
    });
  },
  /**
   * 切换图片视频
   */
  changeAct: function(event) {
    var _type = event.currentTarget.dataset.type;
    this.setData({
      isselect: _type
    })
  },

  /**全部商品和进入店铺的底部跳转 */
  switchTablink(e) {
    var url = e.currentTarget.dataset.url;
    if (url == null || url == undefined || url == "") return;
    router.switchTab({
      path: url
    });
  },
  /**
   * 改变单位
   */
  onChangeGoodsUnitEvent: function(e) {
    let that = this;
    let { goodSpecific, productData } = this.data;
    let { goodsid, gidx, idx } = e.currentTarget.dataset;

    let unit = goodSpecific[gidx].AuxiliaryUnits[idx];

    let g = goodSpecific[gidx];

    g.Translated = unit.Translated;
    g.DefaultUnit = unit.Name;
    g.PriceType = 0;
    g.ZIndex = idx;
    productData.presell = true;
    // productData.DefaultUnit = g.DefaultUnit;
    goodSpecific[gidx] = g;

    //如果基础单位设置了倍数购买，计算当前数量最近的倍数值
    if(g.Translated==1 && productData.MultipleBuy > 0){
      let _rate = Math.ceil(util.precisionDiv(g.CartCount, productData.MultipleBuy))
      g.CartCount = util.precisionX(_rate, productData.MultipleBuy)
    }

    //获得阶梯价格
    var data = {
      translated: g.Translated,
      rule: g.PriceRule || g.PriceRules,
      priceType: g.PriceType
    };
    var price_obj = group.parseRule(data, g.CartCount);
    if (price_obj.has) {
      //如果价格没有变化时，则不给数据源重新绑定值
      if (g.SalesPrice != price_obj.price || (g.SalesIntegral || 0) != (price_obj.integral || 0)) {
        g.SalesIntegral = price_obj.integral;
        g.SalesPrice = price_obj.price;      
      }
    }
    // console.log(productData,'========productData',goodSpecific)
    that.setData({
      goodSpecific: goodSpecific,
      productData: productData,
      current_sku_item: g
    });
  },
  /**
   * 单击事件，获得goodsid（模版中不能使用wx:for-index
   */
  onClickGoodsUnitEvent: function(e) {
    var index = 0;
    if (this.data.pagetype == 1 && this.data.groupType == 2) {
      var goodSpecific = this.data.goodSpecific;
      for (var i in goodSpecific) {
        if (goodSpecific[i].GroupItemId == this.data.productData.GroupItemId) {
          index = i;
          break;
        }
      }
    } else {
      index = e.currentTarget.dataset.gidx;
    }
    this.setData({
      current_gooods_idx: index
    });
  },

  /**加载商品扩展信息 */
  loadProductRelate() {
    var that = this;
    detail.loadProductRelate(this.data.productId, function(res) {
      that.setData({
        Relate: res
      });
    });
  },
  onUnload: function(e) {
    this.data.pre_page = this.getPreData();
    this.data.pre_page.data.is_search = true;
  },
  getPreData: function() {
    const pages = getCurrentPages();
    const length = pages.length;
    const prePage = pages[length - 2]; //上一页
    return prePage;
  },
  /**
 * 打开分享弹层
 */
  showShare: function (e) {
    var that = this;
    dialog.showModal(that, 'showModalStatus')
  },
  /**
   * 隐藏遮罩层
   */
  hideModal: function () {
    dialog.hideModal(this, 'showModalStatus')
  },
  /**
   * 显示海报
   */
  showPoster: function () {
    dialog.hideModal(this, 'showModalStatus')
    this.drawPicture();
    this.setData({
      showPosterShadow: true
    })
  },
  /**
   * 关闭海报
   */
  hidePoster: function () {
    this.setData({
      showPosterShadow: false,
      saveBtn: false
    })
  },
  initData: function (res) {
    let that = this;
    that.setData({
      normalPageX:
        (res.windowWidth * 0.74 - res.windowWidth * 0.67) / 2, //左边文本图片X轴位置
      boxWidth: res.windowWidth * 0.74, //分享图片box宽度
      boxheight: res.windowWidth * (0.222 + 0.72 + 0.192) + 20, //分享图片box高度
      boxPageY: 0, //boxY轴位置
      imgWidth: res.windowWidth * 0.67, //商品图片宽度
      imgHeight: res.windowWidth * 0.92, //商品图片高度
      imgPageY: res.windowWidth * 0.15, //商品图片Y轴位置
      codeWidth: res.windowWidth * 0.192, //小程序码图片宽度
      codeHeight: res.windowWidth * 0.192, //小程序码图片高度
      codePageY:res.windowWidth * 0.9, //小程序码Y轴位置
      pricePageY:res.windowWidth * 0.85 + 30 , //价格Y轴位置
      titlePageY:res.windowWidth * 0.85 + 70, //标题Y轴位置
      subTitlePageY:res.windowWidth * 0.85 + 140, //副标题Y轴位置
      contentTitle: that.data.productData.ProductName,
      subTitle:that.data.productData.PromotionTitle,
      market:that.data.productData.market,
      price: that.data.productData.MinPrice,//that.data.productData.MinPrice 
      logoWidth: res.windowWidth * 0.05 * 5.5,
      logoHeight: res.windowWidth * 0.05,
    });
    let { imgDomain } = this.data;
    if (that.data.logo != "" && that.data.downlogo == "") {
      wx.downloadFile({
        url: imgDomain.replace("http://", "https://") + that.data.logo,
        success: function (res) {
          that.setData({
            downlogo: res.tempFilePath
          });

        },
        fail: function (err) {
          util.tips(err.errMsg);
         }
      });
    }
    //网络图片转为本地图片，直接显示网络图片的话真机不显示
    let swiperImg = this.data.swiperImg || []
    let src = ''
    if (swiperImg.length > 0) {
      src = swiperImg[0].Src
    }
    var url = this.data.imgDomain + src;
    if (url != undefined && url != "") {
      that.setData({
        posterPic: url
      })
      that.getTempFile(url);
    } else {
      that.setData({
        showPosterShadow: false
      }, function () {
        util.tips("未能生成海报图");
        return;
      })
    }
  },
  //绘制海报
  drawPicture: function () {
    let that = this;
    //获取设备信息高度。计算出其他的高度等
    wx.getSystemInfo({
      success: function (res) {
        //调整海报清晰度
        that.setData({
          windowWidth: res.windowWidth * 2,
          windowHeight: res.windowHeight * 2,
          canvasId: "canvas"
        });
        res.windowWidth = res.windowWidth * 2;
        res.windowHeight = res.windowHeight * 2;
        that.initData(res);
      }
    });

  },
  //临时图片路径
  getTempFile: function (url) {
    let that = this;
    let {
      imgDomain,
      imgWidth,
      imgHeight,
      windowWidth
    } = this.data;
    wx.getImageInfo({
      src: url.replace("http://", "https://"),
      success: function (res) {
        console.log(url, res)
        that.setData({
          goodsInfoImg: res.path
        });
        // 获取图片真实信息，防止图片变形
        if (imgWidth) {
          imgHeight = imgWidth * res.height / res.width
          that.setData({
            imgWidth,
            imgHeight,
          })
          // 并且计算图片高度变化后的Y轴值
          let imgPageY = windowWidth * 0.15 + (windowWidth * 0.92 - imgHeight) / 2
          if ((imgPageY + imgHeight) < windowWidth * 1.07) {
            that.setData({
              imgPageY
            })
          }
        }
        //继续生成商品的小程序码
        that.downloadSkuQrCode();
      },
      fail: function (err) {
        console.info(err);
        util.tips(imgDomain + err.errMsg);
      }
    });
  },
  //画矩形，也是整块画布的大小，宽度是屏幕宽度，高度根据内容多少来动态设置。
  drawSquare: function (ctx, height) {
    let that = this;
    ctx.rect(
      0,
      0,
      that.data.boxWidth,
      height
    );
    ctx.setFillStyle("#fff");
    ctx.fill();
  },

  // 设置文字大小，并填充颜色。
  drawTitleFont: function (ctx) {
    let that = this;
    let str = that.data.contentTitle;
    let firstline;
    let secondline;
    //一行显示14个字，超过一行时
    if (str.length > 14) {
      //第一行截取前14个字符
      firstline = str.substring(0, 14);
      //两行都显示不下
      if (str.length > 28) {
        secondline = str.substr(14, 14) + "...";
      } else {
        //第二行取剩下的
        secondline = str.substr(14, str.length - 14);
      }
    } else {
      //一行就能显示时候
      firstline = str;
    }

    ctx.setFontSize(24);
    ctx.setFillStyle("#333");
    let titlePageY;
    if(that.data.subTitle&&that.data.subTitle.length>0){
      titlePageY = that.data.titlePageY;
    }else{
      titlePageY = that.data.titlePageY+40;
    }
    ctx.fillText(firstline, that.data.normalPageX, titlePageY);
    if (secondline) {
      ctx.setFontSize(24);
      ctx.setFillStyle("#333");
      ctx.fillText(
        secondline,
        that.data.normalPageX,
        titlePageY + 34
      );
    }
  },
  // 设置副标题文字大小，并填充颜色。
  drawSubTitleFont: function (ctx) {
    let that = this;
    let str = that.data.subTitle;
    let firstline;
    let secondline;
    //一行显示14个字，超过一行时
    if (str.length > 14) {
      //第一行截取前14个字符
      firstline = str.substring(0, 14);
      //两行都显示不下
      if (str.length > 28) {
        secondline = str.substr(14, 14) + "...";
      } else {
        //第二行取剩下的
        secondline = str.substr(14, str.length - 14);
      }
    } else {
      //一行就能显示时候
      firstline = str;
    }

    ctx.setFontSize(20);
    ctx.setFillStyle("#666");
    ctx.fillText(firstline, that.data.normalPageX, that.data.subTitlePageY);
    if (secondline) {
      ctx.setFontSize(20);
      ctx.setFillStyle("#666");
      ctx.fillText(
        secondline,
        that.data.normalPageX,
        that.data.subTitlePageY + 30
      );
    }
  },
  //绘制促销信息
  drawMarket:function(ctx){
    let that = this;
    let marketTxt = that.data.pagetype==1?'拼团':'预售';
    let priceWidth = ctx.measureText(that.data.Currency + that.data.price).width;
    let originLeft = priceWidth+that.data.normalPageX;
    ctx.strokeStyle = "#cb4255";
    ctx.strokeRect(originLeft+10,that.data.pricePageY-20,60,30);
    ctx.setFontSize(20);
    ctx.setFillStyle("#cb4255");
    ctx.fillText(marketTxt, originLeft+20, that.data.pricePageY);
  },
  // 根据文字多少动态计算高度，然后依次画出矩形，文字，横线和小程序码。
  createNewImg: function () {
    let that = this;
    let ctx = wx.createCanvasContext(that.data.canvasId);
    let contentHeight = that.data.boxheight;
    that.drawSquare(ctx, contentHeight);
    that.setData({
      contentHeight: contentHeight
    });
    // let height = 100;
    // for (let item of that.data.thinkList) {
    //   if (item !== "a") {
    //     that.drawFont(ctx, item, height);
    //     height += that.data.lineHeight;
    //   }
    // }
    that.drawTitleFont(ctx);
    if(that.data.subTitle&&that.data.subTitle.length>0){
      that.drawSubTitleFont(ctx);
    }
    //商城logo

    ctx.drawImage(
      that.data.downlogo,
      (that.data.boxWidth - that.data.logoWidth) / 2,
      (that.data.imgPageY-that.data.logoHeight)/2,
      that.data.logoWidth,
      that.data.logoHeight
    );
    if (that.data.goodsInfoImg != "") {
      //商品图片
      ctx.drawImage(
        that.data.goodsInfoImg,
        that.data.normalPageX,
        that.data.imgPageY,
        that.data.imgWidth,
        that.data.imgHeight
      );
    }
    // 填充价格符号￥
    ctx.setFillStyle("#cb4255");
    ctx.font = "normal normal 30px sans-serif";
    ctx.fillText(that.data.Currency, that.data.normalPageX - 2, that.data.pricePageY);
    // 填充价格文字
    ctx.font = "normal bold 40px sans-serif";
   
    ctx.fillText(
      that.data.pagetype==1?that.data.productData.MinPrice || that.data.productData.NowPrice+(that.data.productData.IsSingle?'':'起')+'/'+(that.data.productData.Unit):that.data.price+'/'+that.data.productData.AuxUnit,
      that.data.normalPageX + 26,
      that.data.pricePageY
    );
    // 计算价格符号￥ + 价格文字宽度
    let priceWidth = ctx.measureText(that.data.Currency + that.data.pagetype==1?that.data.productData.MinPrice ||that.data.productData.NowPrice+(that.data.productData.IsSingle?'':'起')+'/'+that.data.productData.Unit:that.data.price+'/'+that.data.productData.AuxUnit).width;
    //有划线价，才展示
    if (this.data.delPrice) {
      // 填充划线价文字
      ctx.setFillStyle("#999");
      ctx.font = "normal normal 26px sans-serif";
      ctx.fillText(
        that.data.delPrice,
        that.data.normalPageX + priceWidth,
        that.data.pricePageY
      );
      // 计算划线价宽度
      let delPriceWidth = ctx.measureText(that.data.delPrice).width;
      // 填充划线价横线
      ctx.beginPath();
      ctx.moveTo(
        that.data.normalPageX + priceWidth + 2,
        that.data.pricePageY - 4
      );
      ctx.lineTo(
        that.data.normalPageX + priceWidth + delPriceWidth + 2,
        that.data.pricePageY - 4
      );
      ctx.setStrokeStyle("#999");
      ctx.stroke();
      ctx.closePath();
    }
    //绘制促销
    that.drawMarket(ctx);
    // 填充小程序码
    ctx.drawImage(
      that.data.qrCode,
      that.data.normalPageX + that.data.windowWidth * 0.43,
      that.data.codePageY,
      that.data.codeWidth,
      that.data.codeHeight
    );
    // 填充长按立即购买文本
    ctx.setFillStyle("#333");
    ctx.font = "normal normal 18px sans-serif";
    ctx.fillText(
      "扫描/长按识别",
      that.data.normalPageX +
      that.data.windowWidth * 0.43 +
      (that.data.codeWidth - 108) / 2,
      that.data.codePageY + that.data.codeWidth + 20
    );
    ctx.draw(false, function () {
      wx.canvasToTempFilePath({
        canvasId: 'canvas',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          that.setData({
            tempFilePath,
            saveBtn: true
          })
        },
        fail: function (err) {
          console.info(err);
        }
      });
    }); //绘制到canvas
  },

  //下载小程序码
  downloadSkuQrCode: function () {
    let that = this;
    const currentRoute = that.getCurrentPageUrlWithArgs();
    profile.load_wx_qrcode(currentRoute, function (content) {
      if (content != "") {
        var url = "data:image/png;base64," + content;
        that.setData({
          preQR: url
        })
        util.base64src(url, function (res) {
          url = res;
          that.setData({
            qrCode: url
          });
          that.createNewImg();
        });
      } else {
        that.setData({
          showPosterShadow: false
        }, function () {
          util.tips("未能生成小程序码");
          return;
        })
      }

    });

  },

  //点击保存到相册
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    wx.saveImageToPhotosAlbum({
      filePath: that.data.tempFilePath,
      success(res) {
        wx.hideLoading();
        // utils.aiCardActionRecord(19);
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) { }
          },
          fail: function (res) { }
        })
      },
      fail: function (res) {
        wx.hideLoading();
        wx.showToast({
          title: "保存失败",
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  getCurrentPageUrlWithArgs: function () {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const url = currentPage.route
    const options = currentPage.options
    let urlWithArgs = options.id ? options.id : 0;
    urlWithArgs += "_" + (options.ptype ? options.ptype : 0);
    urlWithArgs += "_" + (options.productId ? options.productId : 0);
    urlWithArgs += "_" + (options.discountid ? options.discountid : 0);
    urlWithArgs += "_" + (options.discounttype ? options.discounttype : 0);
    return {
      url,
      urlWithArgs
    }
  },
  /**跳转到首页页面 */
  onBindHome(){
    router.switchTab({
      path: 'index'
    });
  },
  wxParseTagATap(e) {
    let event = e.detail.event || {currentTarget: {dataset: {src: ''}}}
    var url = event.currentTarget.dataset.src;
    theme.linkTo(url);
  },
})